// pages/detail/detail.js - 详情页面（课程/动态）
const { api } = require('../../utils/api')
const { formatRelativeTime } = require('../../utils/util')

Page({
  data: {
    pageType: 'course', // 'course' | 'post' | 'news'
    userAvatar: '', // 当前用户头像
    // 课程详情数据
    courseInfo: {
      id: 1,
      title: '全身燃脂·高效训练',
      image: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/0623c7a580d8110b2319fe65b06d4dd2.png',
      duration: '25分钟',
      calories: '200',
      level: '中级',
      tags: ['全身', '燃脂', '高效'],
      favorited: false,
      completedChapters: 3,
      totalChapters: 8,
      progress: 37,
      description: '这是一套专门针对全身燃脂的高效训练课程，通过科学的动作组合，帮助你在短时间内达到最佳的燃脂效果。适合有一定运动基础的人群。',
      chapters: [
        { id: 1, title: '热身准备', duration: '3分钟', completed: true },
        { id: 2, title: '核心激活', duration: '5分钟', completed: true },
        { id: 3, title: '全身燃脂', duration: '12分钟', completed: true },
        { id: 4, title: '力量训练', duration: '8分钟', completed: false },
        { id: 5, title: '有氧训练', duration: '6分钟', completed: false },
        { id: 6, title: '拉伸放松', duration: '4分钟', completed: false },
        { id: 7, title: '总结回顾', duration: '2分钟', completed: false },
        { id: 8, title: '进阶挑战', duration: '5分钟', completed: false }
      ]
    },
    // 动态详情数据
    postDetail: null,
    // 评论相关
    comments: [],
    commentInput: '',
    loadingComments: false,
    // 其他
    notes: '',
    recommendations: [
      {
        id: 2,
        title: '核心力量训练',
        image: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/c6028ae9aff08b3818e5c6d448c37e81.png',
        duration: '15分钟'
      },
      {
        id: 3,
        title: '腰背舒缓放松',
        image: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/72a798a011746ce7e5bf5434d1a7f226.png',
        duration: '20分钟'
      }
    ]
  },

  onLoad(options) {
    console.log('详情页面加载完成', options);
    const { type, id } = options;
    
    this.setData({ pageType: type || 'course' });
    
    // 获取用户头像（用于底部评论栏）
    const app = getApp();
    if (app.globalData.userInfo) {
      this.setData({
        userAvatar: app.globalData.userInfo.avatar
      });
    }
    
    if (type === 'course') {
      this.loadCourseDetail(id);
    } else if (type === 'news') {
      this.loadNewsDetail(id);
    } else if (type === 'post') {
      this.loadPostDetail(id);
    }
  },

  // 加载课程详情
  loadCourseDetail(id) {
    // 这里可以根据id从服务器加载课程详情
    console.log('加载课程详情', id);
  },

  // 加载资讯详情
  loadNewsDetail(id) {
    // 这里可以根据id从服务器加载资讯详情
    console.log('加载资讯详情', id);
  },

  // 加载动态详情
  loadPostDetail(id) {
    console.log('加载动态详情', id);
    wx.showLoading({ title: '加载中...' });
    
    api.community.getPostDetail(id)
      .then(res => {
        console.log('动态详情返回', res);
        const post = res.data;
        
        // 解析图片
        let images = [];
        try {
          if (post.imageUrls) {
            // 尝试标准 JSON 解析
            try {
              images = JSON.parse(post.imageUrls);
            } catch (e) {
              // 如果失败，尝试处理非标准格式 [url1,url2]
              console.log('尝试解析非标准格式的imageUrls:', post.imageUrls);
              const urlStr = post.imageUrls.trim();
              if (urlStr.startsWith('[') && urlStr.endsWith(']')) {
                // 移除首尾的方括号
                const content = urlStr.slice(1, -1);
                // 按逗号分割（注意：URL中可能包含逗号，使用http作为分隔标志）
                images = content.split(/,(?=http)/).map(url => url.trim());
              }
            }
            console.log('解析后的图片数组:', images);
          }
        } catch (e) {
          console.error('解析图片失败', e, post.imageUrls);
        }
        
        // 格式化时间
        let timeStr = '刚刚';
        if (post.createTime) {
          try {
            const timestamp = new Date(post.createTime).getTime();
            timeStr = formatRelativeTime(timestamp);
          } catch (e) {
            timeStr = post.createTime;
          }
        }
        
        this.setData({
          postDetail: {
            postId: post.postId,
            userId: post.userId,
            username: post.createBy || '运动达人',
            avatar: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/f393f5c29478a7b382748e71c1d68ebb.png',
            time: timeStr,
            content: post.content || '',
            images: images,
            likes: post.likeCount || 0,
            comments: post.commentCount || 0,
            collects: post.collectCount || 0,
            shares: post.shareCount || 0,
            views: post.viewCount || 0,
            liked: false, // 后端暂未返回，默认false
            collected: false // 后端暂未返回，默认false
          }
        });
        
        // 加载评论
        this.loadComments(id);
        
        wx.hideLoading();
      })
      .catch(err => {
        console.error('加载动态详情失败', err);
        wx.hideLoading();
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
      });
  },
  
  // 加载评论列表
  loadComments(postId) {
    this.setData({ loadingComments: true });
    
    api.community.getPostComments(postId)
      .then(res => {
        console.log('评论列表', res);
        const comments = (res.data && res.data.list) || [];
        this.setData({
          comments: comments,
          loadingComments: false
        });
      })
      .catch(err => {
        console.error('加载评论失败', err);
        this.setData({ loadingComments: false });
      });
  },

  
  // 切换点赞（动态）
  togglePostLike() {
    if (!this.data.postDetail) return;
    
    const post = this.data.postDetail;
    const newLiked = !post.liked;
    
    // 乐观更新
    this.setData({
      'postDetail.liked': newLiked,
      'postDetail.likes': newLiked ? post.likes + 1 : post.likes - 1
    });
    
    // 调用API
    const apiCall = newLiked ? api.community.likePost : api.community.unlikePost;
    apiCall(post.postId)
      .then(() => {
        wx.showToast({
          title: newLiked ? '已点赞' : '已取消',
          icon: 'success'
        });
      })
      .catch(err => {
        console.error('点赞操作失败', err);
        // 回滚
        this.setData({
          'postDetail.liked': post.liked,
          'postDetail.likes': post.likes
        });
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        });
      });
  },
  
  // 切换收藏（动态）
  togglePostCollect() {
    if (!this.data.postDetail) return;
    
    const post = this.data.postDetail;
    const newCollected = !post.collected;
    
    // 乐观更新
    this.setData({
      'postDetail.collected': newCollected,
      'postDetail.collects': newCollected ? post.collects + 1 : post.collects - 1
    });
    
    // 调用API（占位）
    const apiCall = newCollected ? api.community.collectPost : api.community.uncollectPost;
    apiCall(post.postId)
      .then(() => {
        wx.showToast({
          title: newCollected ? '已收藏' : '已取消收藏',
          icon: 'success'
        });
      })
      .catch(err => {
        console.error('收藏操作失败', err);
        // 回滚
        this.setData({
          'postDetail.collected': post.collected,
          'postDetail.collects': post.collects
        });
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        });
      });
  },
  
  // 评论输入
  onCommentInput(e) {
    this.setData({
      commentInput: e.detail.value
    });
  },
  
  // 提交评论
  submitComment() {
    const content = this.data.commentInput.trim();
    if (!content) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.postDetail) return;
    
    wx.showLoading({ title: '发送中...' });
    
    api.community.addPostComment({
      postId: this.data.postDetail.postId,
      content: content
    })
      .then(() => {
        wx.hideLoading();
        wx.showToast({
          title: '评论成功',
          icon: 'success'
        });
        
        // 清空输入框
        this.setData({ commentInput: '' });
        
        // 重新加载评论
        this.loadComments(this.data.postDetail.postId);
        
        // 更新评论数
        this.setData({
          'postDetail.comments': this.data.postDetail.comments + 1
        });
      })
      .catch(err => {
        console.error('评论失败', err);
        wx.hideLoading();
        wx.showToast({
          title: '评论失败',
          icon: 'none'
        });
      });
  },
  
  // 预览图片
  previewImage(e) {
    const { url, images } = e.currentTarget.dataset;
    wx.previewImage({
      current: url,
      urls: images || [url]
    });
  },

  // 跳转到评论详情页
  goToCommentPage() {
    const { postDetail } = this.data;
    if (!postDetail) return;
    
    const title = encodeURIComponent(postDetail.content.substring(0, 50));
    wx.navigateTo({
      url: `/pages/comment/comment?postId=${postDetail.postId}&title=${title}&commentCount=${postDetail.comments}`
    });
  },

  // 播放视频
  playVideo() {
    wx.navigateTo({
      url: '/pages/video/video?id=' + this.data.courseInfo.id
    });
  },

  // 开始训练
  startTraining() {
    wx.navigateTo({
      url: '/pages/video/video?id=' + this.data.courseInfo.id
    });
  },

  // 切换收藏
  toggleFavorite() {
    this.setData({
      'courseInfo.favorited': !this.data.courseInfo.favorited
    });
    
    wx.showToast({
      title: this.data.courseInfo.favorited ? '已收藏' : '已取消收藏',
      icon: 'success'
    });
  },

  // 分享课程
  shareCourse() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  // 播放章节
  playChapter(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/video/video?chapterId=${id}`
    });
  },

  // 笔记输入
  onNotesInput(e) {
    this.setData({
      notes: e.detail.value
    });
  },

  // 保存笔记
  saveNotes() {
    if (!this.data.notes.trim()) {
      wx.showToast({
        title: '请输入笔记内容',
        icon: 'none'
      });
      return;
    }

    // 这里可以保存笔记到服务器
    wx.showToast({
      title: '笔记保存成功',
      icon: 'success'
    });
  },

  // 跳转到课程
  goToCourse(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?type=course&id=${id}`
    });
  },

  // 分享给朋友
  onShareAppMessage() {
    return {
      title: this.data.courseInfo.title,
      path: `/pages/detail/detail?type=course&id=${this.data.courseInfo.id}`,
      imageUrl: this.data.courseInfo.image
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: this.data.courseInfo.title,
      imageUrl: this.data.courseInfo.image
    };
  }
});